home *** CD-ROM | disk | FTP | other *** search
/ Eagles Nest BBS 8 / Eagles_Nest_Mac_Collection_Disc_8.TOAST / Developer Tools⁄Additions / IntermediatC / Ships #6 / teacher's compute.c < prev    next >
C/C++ Source or Header  |  1990-10-25  |  2KB  |  76 lines

  1. /*
  2.  
  3. COMPUTE.C
  4.  
  5. Ships at Sea:
  6.  
  7. Create 25 ship locations (x,y) between -100 and 100 for each x and y.  Determine
  8. which 2 of the 25 ships are closest together.  Print the locations of all ships
  9. and the numbers of the 2 closest ships.  Three modules must be used:
  10.  
  11. control.c        contains main()
  12. compute.c        creates the ship locations and locates the 2 closest ships
  13. output.c        prints data to disk
  14.  
  15. */
  16.  
  17. /*
  18.  
  19. This is compute.c.  This module will create a list of ship
  20. locations and determine the closest pair.
  21.  
  22. */
  23.  
  24.  
  25. #include <stdlib.h>            /* used for rand() declaration */
  26.  
  27.  
  28. #define square_of(x)        ((x) * (x))
  29. #define random(a,b)            (rand() % ((b) - (a)) + (a))
  30. #define LOW_VALUE            -100
  31. #define HIGH_VALUE            100
  32.  
  33.  
  34. void create_locations
  35.        (double latitudes[], double longitudes[], int no_of_ships);
  36. void locate_nearest_pair
  37.        (int nearest_subscripts[], double latitudes[], double longitudes[],
  38.         int no_of_ships);
  39.  
  40.  
  41. void create_locations
  42.        (double latitudes[], double longitudes[], int no_of_ships)
  43.    {
  44.    int i;
  45.  
  46.    for (i = 0; i < no_of_ships; i++)
  47.       {
  48.       latitudes[i] = random(LOW_VALUE, HIGH_VALUE);
  49.       longitudes[i] = random(LOW_VALUE, HIGH_VALUE);
  50.       }
  51.    }
  52.  
  53.  
  54. void locate_nearest_pair
  55.        (int nearest_subscripts[], double latitudes[], double longitudes[],
  56.         int no_of_ships)
  57.    {
  58.    int i, j;
  59.    double distance_squared, new_distance;
  60.    
  61.    distance_squared = HIGH_VALUE - LOW_VALUE;
  62.    distance_squared = 2.0 * square_of(distance_squared);
  63.    for (i = 0; i < no_of_ships; i++)
  64.       for (j = i + 1; j < no_of_ships; j++)
  65.          {
  66.          new_distance = square_of(latitudes[i] - latitudes[j])
  67.                  + square_of(longitudes[i] - longitudes[j]);
  68.          if (new_distance < distance_squared)
  69.             {
  70.             distance_squared = new_distance;
  71.             nearest_subscripts[0] = i;
  72.             nearest_subscripts[1] = j;
  73.             }
  74.          }
  75.    }
  76.